import 'package:dio/dio.dart';
import 'package:flutter_home_manager/constants/idnex.dart';
import 'package:flutter_home_manager/utils/RequestDio.dart';

class Diorequest {
  final _dio = Dio();

//构造函数
  DioRequest() {
    // //基地址
    // _dio.options.baseUrl = GlobalVariable.BASE_URL;
    // //连接超时时长
    // _dio.options.connectTimeout =
    //     const Duration(seconds: GlobalVariable.NEW_WORK_TIME_OUT);
    // //接收超时时长
    // _dio.options.receiveTimeout=
    //     const Duration(seconds: GlobalVariable.NEW_WORK_TIME_OUT);

    //flutter简写
    _dio
      ..options.baseUrl = GlobalVariable.BASE_URL
      ..options.connectTimeout =
          const Duration(seconds: GlobalVariable.NEW_WORK_TIME_OUT)
      ..options.receiveTimeout =
          const Duration(seconds: GlobalVariable.NEW_WORK_TIME_OUT)
      ..interceptors.add(
        InterceptorsWrapper(
          onRequest: (context, handler) {
            //请求拦截器

            //注入token等等

            handler.next(context);
          },
          onResponse: (context, handler) {
            //响应拦截器
            handler.next(context);
          },
          onError: (context, handler) {
            //错误拦截器
            handler.reject(context);
          },
        ),
      );
  }

  //dynamic 类似于字面量any，表示可以类型不定
  get(String url, {Map<String, dynamic>? params}) async {
    return _handleResponse(_dio.get(url, queryParameters: params));
  }

  post(String url, {Map<String, dynamic>? data}) {
    return _handleResponse(_dio.post(url, data: data));
  }

  put(String url, {Map<String, dynamic>? data}) {
    return _handleResponse(_dio.put(url, data: data));
  }

  delete(String url,
      {Map<String, dynamic>? data, Map<String, dynamic>? params}) {
    return _handleResponse(
        _dio.delete(url, data: data, queryParameters: params));
  }

  upload(String url) {}

  _handleResponse(Future<Response<dynamic>> task) async {
    final res = await task;
    if (res.data["code"] == GlobalVariable.SUCESS_CODE) {
      return res.data["data"];
    }
    //错误信息
    throw DioException(requestOptions: res.requestOptions); //抛出异常
  }
}

final dioRequest = Diorequest();
